﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LogBookImporter.Implementation
{
    public class LogBookLineParser
    {

        private static readonly string _fileRowDelimiter = ConfigurationManager.AppSettings["FileDelimiter"];
        private static readonly string _angleDelimiter = ConfigurationManager.AppSettings["AngleDelimiter"];
        private static readonly string _deltaDelimiter = ConfigurationManager.AppSettings["FileNameDeltaIncrementDelimiter"];
        private static readonly string _scansDelimiter = ConfigurationManager.AppSettings["ScansDelimiter"];
        private static readonly string _resolutionDelimiter = ConfigurationManager.AppSettings["ResolutionDelimiter"];
        private static readonly string _dateDelimiter = ConfigurationManager.AppSettings["DateDelimiterInFileLocation"];
        private static readonly string _hourMinuteDelimiter = ConfigurationManager.AppSettings["HourMinuteDelimiter"];

        public static string[] ParseMainLine(string mainline)
        {
            string[] separators = new string[] { _fileRowDelimiter };
            string[] elements = mainline.Split(separators, StringSplitOptions.None);
            
            return elements;
        }


        public static string ParseFileLocation(string filestring)
        {
            string[] separators = { _deltaDelimiter };
            string[] elements = filestring.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            int incrementNumber = int.Parse(elements[1]);
            int incrementDelta = incrementNumber-1;
            string fileLocation = elements[0];

            if (incrementNumber == 1) {
                return fileLocation;
            }

            return CreateFileLocationByDelta(fileLocation, incrementNumber - 1);
        }

        public static int ParseDelta(string filenameAndDelta) {
            string[] separators = { _deltaDelimiter };
            string[] elements = filenameAndDelta.Split(separators, StringSplitOptions.RemoveEmptyEntries);
           return int.Parse(elements[1]);
        }

        public static string CreateFileLocationByDelta(string fileLocation, int delta) {
            char lastChar = fileLocation[fileLocation.Length - 1];
            lastChar += (char)delta;
            StringBuilder incrementedStringBuilder = new StringBuilder();
            incrementedStringBuilder.Append(fileLocation.Substring(0, fileLocation.Length - 1));
            incrementedStringBuilder.Append(lastChar);
            return incrementedStringBuilder.ToString();
        }

        public static double[] ParseAngles(string anglesString)
        {
            string[] separators = { _angleDelimiter };
            string[] elements = anglesString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            double [] angles = new double[]{double.Parse(elements[0]), double.Parse(elements[1])};
            return angles;
        }

        public static int ParseScans(string scansString)
        {
            string[] separators = { _scansDelimiter };
            string[] elements = scansString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            int numscans = int.Parse(elements[0]);
            return numscans;
        }

        public static double ParseResolution(string resString)
        {
            string[] separators = { _resolutionDelimiter };
            string[] elements = resString.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            return double.Parse(elements[1]);
        }

        /// <summary>
        /// C:\elli\0802feb\\feb01a
        /// Equals to February 1th 2008
        /// </summary>
        /// <param name="time">08:23</param>
        /// <param name="fileLocation">C:\elli\0802feb\\feb01a</param>
        /// <returns></returns>
        public static DateTime ParseDateTimeFromFileLocation(string time, string fileLocation) {
            string[] delimiter = new string[] { _dateDelimiter,  };
            string[] dateParts = fileLocation.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
            string last = dateParts[dateParts.Length-1];
            string secondLast = dateParts[dateParts.Length-2];
            time = FormatTime(time);
            Regex regex = new Regex(@"^\d\d");
            if (regex.IsMatch(last)) {
                last = last.Substring(2, last.Length-2);
            }
            string dateString = string.Format("{0}{1}{2}", secondLast.Substring(0, 4), last.Substring(3, 2), time);
            return DateTime.ParseExact(dateString, "yyMMddHH:mm", CultureInfo.InvariantCulture);
        }

        private static string FormatTime(string time) {
            if (time.Length == 5) {
                return time;
            }
            
            string[] delimiters = new string[] { _hourMinuteDelimiter };
            string[] timeParts = time.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            if (timeParts[0].Length == 1) {
                timeParts[0] = string.Format("0{0}", timeParts[0]);
            }
            if (timeParts[1].Length == 1) {
                timeParts[1] = string.Format("0{0}", timeParts[1]);
            }
            return string.Format("{0}:{1}", timeParts[0], timeParts[1]);
        }
        
    }
}
